import React,{PureComponent} from "react"
import "./BackTop.less"
import {getScrollTop,moveTo} from "../../utils/helper"

export default class BackTop extends PureComponent{
	constructor(props){
		super(props);
		this.timer="";
		this.state={
			show:false,
			type:""
		}
	}
	showBtn=()=>{
		let top = getScrollTop();
		let {show}=this.state;
		if(top>=600){
			if(!show){
				setTimeout(()=>{
					this.setState({
						type:"enter",
						show:true
					})
					this.timer=setTimeout(()=>{
						this.setState({
							type:""
						})
					},200)
				})
			}
		}
		else{
			if(show){
				setTimeout(()=>{
					this.setState({
						type:"leave",
						show:false
					})
					this.timer=setTimeout(()=>{
						this.setState({
							type:""
						})
					},200)
				},200)
			}
		}
	}
	
	componentDidMount(){
		document.getElementById("root").addEventListener("scroll",this.showBtn,false)
		window.addEventListener("scroll",this.showBtn,false)
	}
	
	componentWillUnmount(){
		document.getElementById("root").removeEventListener("scroll",this.showBtn,false)
		window.removeEventListener("scroll",this.showBtn,false)
	}
	render(){
		let {show,type}=this.state;
		if(!show&&!type){
			return null
		}
		else{
			let className= "mi-back-top";
			if(type=="enter"){
				className+=" enter"
			}
			if(type=="leave"){
				className+=" leave"
			}
			return (
				<div className={className} onClick={()=>{moveTo(0)}}>
					<img src="./image/backtop.png" alt="" />
				</div>
			)
		}
	}
}